import json
from flask import jsonify
from backend.utils import json_to_dataframe, read_json_file


def sort_by_rating(df):
    df_sorted = df.sort_values(by='rating_num', ascending=False)
    df_top10 = df_sorted.head(10)
    return df_top10


def get_top_rated_movies_api(app):
    @app.route('/api/movie/top-rated')
    def get_top_rated_movies():
        input_file = '../output.json'
        json_data = read_json_file(input_file)
        df = json_to_dataframe(json_data)
        df_top10 = sort_by_rating(df)
        data = df_top10.to_dict(orient='records')
        return jsonify({'code': 0, 'data': data, 'message': '请求成功'})
